package com.acme.bankapp.services.email;

import java.util.LinkedList;
import java.util.List;

/**
 * Email Sender class
 * 
 */
public class EmailService {

	private List<Email> emails = new LinkedList<Email>();

	private EmailSender sender;

	private volatile boolean isClosed = false;

	public EmailService() {
		sender = new EmailSender();
		sender.start();
	}

	/**
	 * Add email to sending list.
	 * 
	 * @param email
	 */
	public void addEmailToSendingList(Email email) {
		if (isClosed)
			throw new IllegalStateException("Service already closed!");

		synchronized (emails) {
			emails.add(email);
			emails.notifyAll();
		}

	}

	/**
	 * Close service. All emails from queue will be send. Adding new elements
	 * will be prevented
	 */
	public void closeService() {
		isClosed = true;
		synchronized (emails) {
			emails.notifyAll();
		}
		sender.interrupt();
	}

	class EmailSender extends Thread {
		@Override
		public void run() {

			while (true) {
				Email email;
				synchronized (emails) {
					email = getEmailFromQueue();
				}
				if (email == null)
					return;
				sendEmail(email);
			}

		}

		private Email getEmailFromQueue() {
			while (emails.isEmpty()) {
				if (isInterrupted()) return null;
				try {
					emails.wait();
				} catch (InterruptedException e) {
					System.err.println("Email service was interrupted!");
					if(emails.isEmpty()) return null;
				}
			}
			return emails.remove(0);
		}

		/**
		 * Possible long operation...
		 * 
		 * @param email
		 */
		private void sendEmail(Email email) {
			System.out.println("EmailSended\n" + email);
		}
	}

}
